package com.csx.governance.traffic.route;

import cn.hutool.core.collection.CollectionUtil;
import com.csx.governance.traffic.core.context.TrafficMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * <p>抽象的服务实例过滤器</p>
 * <p>抽出服务过滤器的一些公共逻辑,例如打印日志等</p>
 * @author cuisongxu
 * @date 2023/2/25 19:25
 */
public abstract class AbstractFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(AbstractFilter.class);

    @Override
    public final <T> List<T> filter(List<T> serviceInstances, Function<T, Map<String, String>> metadataMapping, TrafficMessage trafficMessage) {
        if(CollectionUtil.isEmpty(serviceInstances)) {
            return Collections.emptyList();
        }
        logger.debug("before route request: {}, instance size: {}", trafficMessage, serviceInstances.size());
        List<T> filteredServiceInstances = doFilter(serviceInstances, metadataMapping, trafficMessage);
        logger.debug("after route request: {}, instance size: {}", trafficMessage, filteredServiceInstances.size());
        return filteredServiceInstances;
    }

    /**
     * 执行服务实例过滤
     * @param serviceInstances 原实例列表
     * @param metadataMapping 元数据Map
     * @param trafficMessage 请求
     * @param <T> 实例类型
     * @return 过滤后的服务实例列表
     */
    protected abstract <T> List<T> doFilter(List<T> serviceInstances, Function<T, Map<String, String>> metadataMapping, TrafficMessage trafficMessage);
}
